package security.dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import security.model.Role;


@Stateless
public class RoleDAO {
	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	public Role getById(Integer id){	
		return em.find(Role.class, id);
	}
	
	public Role save(Role role) {
    	em.persist(role);
    	return role;
    }
	
    public Role update(Role role) {
    	return em.merge(role);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Role.class, id));
    }
	
	@SuppressWarnings("unchecked")
    public List<Role> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Role e ORDER BY e.id DESC");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    // ------------------------------------------------------------------------------
    
    public Role getByName(String name) {
    	Role result = null;
    	Query query = em.createQuery("SELECT e FROM Role e WHERE e.name=:name");
		query.setParameter("name", name);
		try {
			result = (Role) query.getSingleResult(); 
        }
    	catch (NoResultException e) {
			//e.printStackTrace();
		}    	
        return result;   
    }

}

